<!-- 下单界面，也就是这个页面确定之后生成订单 -->
<template>
  <div class="settle-card">
    <h1 class="title">订单预览</h1>
    <el-divider></el-divider>

    <!-- 收货信息 -->
    <div class="address-info">
      <p class="address-info-title">
        <font-awesome-icon :icon="['fas', 'location-dot']" />
        收货信息
        <span style="font-size: 13px; margin-left: 10px; color: #666666;">
          <font-awesome-icon :icon="['fas', 'circle-info']" />
          注：目前订单预览多笔订单只允许选择同一个收货地址。
        </span>
      </p>
      <el-card v-loading="loading || address_loading" shadow="always" style="margin-bottom: 5px; margin-top: 5px;">
        <div style=" display: flex; align-items: center; justify-content: space-between;">
          <div>
            <!-- 信息展示 -->
            <div class="name-phone">
              <span class="name">{{ currentAddress.address.name }}</span>
              <span class="phone-number">{{ currentAddress.address.phoneNumber }}</span>
              <el-tag class="tag" size="small">{{ currentAddress.address.tag }}</el-tag>
            </div>
            <div class="addr">
              <span>{{ currentAddress.address.province }}</span>&emsp13;
              <span>{{ currentAddress.address.city }}</span>&emsp13;
              <span>{{ currentAddress.address.district }}</span>&emsp13;
              <span>{{ currentAddress.address.detail }}</span>
            </div>
          </div>
          <el-button type="primary" @click="drawer = true">更换收货地址</el-button>
        </div>
      </el-card>
    </div>

    <div class="order-detail">
      <el-card v-if="moreInfoList.length > 0" v-for="(item, index) in store.state.order.commodityGroup" shadow="always"
        style="margin-bottom: 20px;" v-loading="loading">

        <!-- 商店名 -->
        <h1 style="font-size: 16px; margin-bottom: 20px; margin-top: 10px;">
          <font-awesome-icon :icon="['fas', 'store']" />
          {{ item[0].storeVo.storeName }}
          <font-awesome-icon :icon="['fas', 'angle-right']" />
        </h1>

        <!-- 商品清单表 -->
        <el-table :data="item" show-summary :summary-method="getSummaries" :border="true">
          <el-table-column label="商品图片" align="center">
            <template v-slot="scope">
              <img :src="img_url_pre(scope.row.commodity.pictures[0])" alt="商品缩略图"
                style="border-radius: 5px; height: 90px; width: 90px;">
            </template>
          </el-table-column>
          <el-table-column label="商品名称" align="center">
            <template v-slot="scope">
              {{ scope.row.commodity.commodityName }}
            </template>
          </el-table-column>
          <el-table-column label="商品单价 / 元" align="center">
            <template v-slot="scope">
              {{ scope.row.commodity.price.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="购买数量" prop="commodityNum" align="center"></el-table-column>
          <el-table-column label="商品总额 / 元" align="center">
            <template v-slot="scope">
              {{ (scope.row.commodity.price * scope.row.commodityNum).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>

        <el-form-item label="配送服务：" style="margin-top: 30px;">
          <span style="font-size: 16px; font-weight: 600;">快递 免邮 送运费险；现货，付款后48小时内发货</span>
        </el-form-item>

        <!-- 订单备注 -->
        <el-form-item label="订单备注：">
          <el-input placeholder="请输入订单备注 :)" v-model="moreInfoList[index].moreInfo"></el-input>
        </el-form-item>

      </el-card>

      <el-divider></el-divider>
      <p>
        <font-awesome-icon :icon="['fas', 'magnifying-glass-dollar']" />
        价格明细
      </p>
      <div class="activity">
        跨店满减活动：
        <el-card v-for="item in activityList" style="margin-right: 10px;" shadow="hover">
          <font-awesome-icon :icon="['fas', 'bookmark']" style="color: #2e64c2;" />
          {{ item.activityName }}
          <div class="detail">满{{ item.reach }}元立减{{ item.reduce }}元</div>
        </el-card>
      </div>
      <div style="margin-top: 40px; display: flex; justify-content: space-between; align-items: center;">
        <div>
          合计：￥<span style="font-size: 30px; color: #ff3e28;">{{ totalAmount.toFixed(2) }}</span>
          <span style="font-size: 13px; margin-left: 10px; color: #666666;">
            <font-awesome-icon :icon="['fas', 'circle-info']" />
            注：跨店满减活动只在结算的时候生效。
          </span>
        </div>
        <div>
          <el-button size="large" type="success" plain round @click="submitOrdersAndPay" :loading="loading">
            提交所有订单，并前往结算
          </el-button>
          <el-button size="large" type="info" plain round>
            取消订单
          </el-button>
        </div>
      </div>

    </div>
  </div>

  <el-drawer v-model="drawer" title="用户收货地址" direction="rtl" size="48%">
    <addresses @changeAddress="changeAddress" :userId="store.state.user.userId"></addresses>
  </el-drawer>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { onMounted, reactive, ref, getCurrentInstance } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex"
import Addresses from "../../../components/Addresses.vue";
import img_url_pre from '../../../utils/img_url_filter'

const { proxy } = getCurrentInstance();
const router = useRouter();
const store = useStore();
const moreInfoList = ref([]);  // 订单的备注列表
const commodityInfoList = ref([]);
const activityList = ref([]);  // 当前如果这几笔订单一同结算的话，会涉及哪些活动
const totalAmount = ref(0);  // 当前如果这几笔订单一同结算的话，总价
const drawer = ref(false);
const loading = ref(false);
const address_loading = ref(false);

const currentAddress = reactive({
  address: {
    "addressId": "",
    "userId": "",
    "name": "",
    "phoneNumber": "",
    "province": "",
    "city": "",
    "district": "",
    "detail": "",
    "tag": "",
    "isDefault": 0
  }
})

/**
 * 获取用户的默认收货地址
 */
const defaultAddress = async () => {
  let ret;
  try {
    ret = await proxy.$api.address.getDefaultAddressOfUser();
  } catch (error) {
    console.log('default address error: ', error);
    ElMessage.error({ showClose: true, message: "您还没有可用的收货地址，请先添加收货地址" });
    // 滚动到顶部
    if (store.state.MallMainScrollBarRef) {
      store.state.MallMainScrollBarRef.setScrollTop(0);
    }
    router.push('/mall/user_center/address');
  }

  if (ret.status === 200 && ret.data) {
    currentAddress.address = ret.data;
    // 更新当前订单预览时选中收货地址
    store.commit('address/updateAddressId', currentAddress.address.addressId);
  }
}

/**
 * 子组件点击选择了一个地址，这里更换当前页面中的地址
 */
const changeAddress = async () => {
  drawer.value = false;

  address_loading.value = true;

  let ret = await proxy.$api.address.getAddress(store.state.address.addressId).catch(error => {
    console.log(error);
  })
  currentAddress.address = ret.data;

  address_loading.value = false;
}

/**
 * 计算一笔订单的总金额
 * @param {object} param 
 */
const getSummaries = (param) => {
  const { columns, data } = param
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '订单总金额'
      return;
    }
    if (index === 4) {
      let tmp_sum = 0;
      data.forEach(item => {
        tmp_sum += item.commodityNum * item.commodity.price;
      });
      sums[index] = `${tmp_sum.toFixed(2)}`;
    }
  })
  return sums;
}

/**
 * 进行订单结算预览
 */
const previewOrders = async () => {
  // 发请求到后端，计算实际总价
  let ret = await proxy.$api.order.orderPreview({
    commodityInfoList: commodityInfoList.value,
  });
  if (ret.status === 200) {
    activityList.value = ret.data.activityList;
    totalAmount.value = ret.data.total;
  }
}

/**
 * 提交所有的订单（真正生成订单），并前往支付界面
 */
const submitOrdersAndPay = async () => {
  loading.value = true;

  let ret;
  if (store.state.order.cartItemIdList.length === 0) {
    // 商品界面直接购买
    ret = await proxy.$api.order.confirmOrder({
      storeId: moreInfoList.value[0].storeId,
      addressId: currentAddress.address.addressId,
      commodityId: commodityInfoList.value[0].commodityId,
      moreInfo: moreInfoList.value[0].moreInfo,
      commodityNum: commodityInfoList.value[0].commodityNum,
    })

    store.commit('order/clearOrderList');
    store.commit('order/pushOrderListItem', ret.data);
  } else {
    // 购物车生成订单
    ret = await proxy.$api.order.confirmOrderFromCart({
      cartItemIdList: store.state.order.cartItemIdList,
      addressId: currentAddress.address.addressId,
      moreInfoList: moreInfoList.value,
    });

    store.commit('order/setOrderList', ret.data);
  }

  if (ret.status === 200) {
    // 滚动到顶部
    if (store.state.MallMainScrollBarRef) {
      store.state.MallMainScrollBarRef.setScrollTop(0);
    }
    ElMessage.success("成功生成订单");
    store.commit('order/reverseToPay');
    router.push('/mall/order/pay');
  }

  loading.value = false;
}

onMounted(async () => {
  loading.value = true;

  await defaultAddress();

  // 构造订单备注列表和订单预览需要的commodityInfoList
  store.state.order.commodityGroup.forEach(group => {
    moreInfoList.value.push({ storeId: group[0].storeVo.storeId, moreInfo: '' });
    group.forEach(item => {
      commodityInfoList.value.push({
        storeId: item.storeVo.storeId,
        commodityId: item.commodity.commodityId,
        commodityNum: item.commodityNum
      });
    });
  });

  // 请求订单总额、满减活动等的预览
  await previewOrders();

  loading.value = false;
})
</script>

<style lang="less" scoped>
.settle-card {
  background-color: white;
  width: 73%;
  margin: 20px auto 50px auto;
  padding: 20px 40px 20px 40px;
  border-radius: 20px;

  .title {
    font-size: 23px;
    margin-top: 5px;
    font-weight: 600;
  }

  .el-divider {
    border-top: 2px solid rgba(170, 165, 165, 0.651);
  }

  .address-info {
    .address-info-title {
      font-size: 16px;
      line-height: 35px;
    }

    .name-phone {
      display: flex;
      align-items: center;

      .name {
        font-size: 16px;
      }

      .phone-number {
        font-size: 15px;
        margin-left: 10px;
      }

      .tag {
        margin-left: 10px;
      }
    }

    .addr {
      margin-top: 15px;
      font-size: 15px;
      color: rgb(147, 150, 152);
      line-height: 23px;
    }
  }

  .order-detail {
    margin-top: 20px;

    .activity {
      margin-top: 20px;
      display: flex;
      align-items: center;
      font-size: 16px;

      .detail {
        font-size: 14px;
        color: gray;
        margin-top: 5px;
      }
    }
  }
}
</style>